// *******************************************************************************************************
// # トップ
//   ・インプットフォーカス
//   ・地域コンテンツの切り替え
//   ・タブの切り替え
//   ・モーダル 位置
//   ・モーダル 希望条件選択
// *******************************************************************************************************

(function(win, doc) {
	/* インプットフォーカス
	----------------------------------- */
	function inputFocus(){
		var inputTextBox = $('#contentHeader .search_blc input:text');

		inputTextBox.each(function(i){
			$(this).focus(function(e){
				$(this).addClass('input-focus');
				if(this.value == this.defaultValue){
					$(this).val('');
				};
			}).blur(function(e){
				if(this.value == ''){
					$(this).val(this.defaultValue).removeClass('input-focus');
				};
			});
			if (this.value != this.defaultValue) {
				$(this).addClass('input-focus');
			};
		});
	};

	/* 地域コンテンツの切り替え
	----------------------------------- */
	function areaChange(){
		var $target = $('.main_cts'),
			SPEED1 = 200,
			SPEED2 = 30000;

		$(document).on('click', 'a.pjax', function(e) {
			e.preventDefault();
			var href = $(this).attr('href');
			$target.stop().animate({ 'opacity': 0 }, SPEED1, 'easeOutQuad', function(e){
				$.pjax({
					url: href,
					container: '.main_cts',
					fragment : '.main_cts',
					timeout : SPEED2
				});
			});
		});
		$(document).on('pjax:end', function(){
			$target.stop().animate({ 'opacity': 1 }, SPEED1, 'easeOutQuad');
			 update_todofuken_links($('#tabSearch li.active'));
		});
	};
	$('.shop, .room').each(function(i){
		$(this).find('a').on('click', function(e){
			e.preventDefault();
			onTabSearchClick(i);
			setStorage(i + 1);
			update_todofuken_links($('#tabSearch li.active'));
			
			var $menulist = $('.list_menu');
			var $menubtn = $('.btn_menu a');
			var $cover = $('#cover');
			
			$menubtn.removeClass('active');
			$menulist.slideToggle(500);
			$cover.animate( {opacity:'toggle',}, {duration:500, easing:'swing',});
			$('a').css('-webkit-tap-highlight-color','');
						
		});
		
		function onTabSearchClick(n){
			$('#tabSearch li').removeClass('active');
			$('#tabSearch li').eq(n).addClass('active');
		};
		
		var storage = localStorage,
		STORAGE_ID = 'sp_top';
		function setStorage(n){
			storage.setItem(STORAGE_ID, n);
		};
		
	});
	/* タブの切り替え
	----------------------------------- */
	function tabChange(){
		var storage = localStorage,
			STORAGE_ID = 'sp_top';

		$('#tabSearch li').each(function(i){
			$(this).find('a').on('click', function(e){
				e.preventDefault();
				onTabSearchClick(i);
				setStorage(i + 1);
				update_todofuken_links($('#tabSearch li.active'));
			});
		});
		function onTabSearchClick(n){
			$('#tabSearch li').removeClass('active');
			$('#tabSearch li').eq(n).addClass('active');
		};
		function setStorage(n){
			storage.setItem(STORAGE_ID, n);
		};
		var _default = storage.getItem(STORAGE_ID);
		if (_default) {
			onTabSearchClick(_default - 1);
		};
		
		//スマホの場合
		if(window.location.href.indexOf('?s') > 0){
			$('#tabSearch').find('#tabShop').trigger('click');
		}
	};

	function update_todofuken_links($this) {
		$('.main_cts a').each(function(index,elem) {
			var $elem = $(elem);
			console.log($elem);
            if (!$elem.hasClass('pjax')) {
				var url=$elem.attr('href');
				url = url.replace(/shop\/$/,"");
				if ($this.hasClass('right')) url+='shop/';
				$elem.attr('href',url);
            }
		});
	}
	
	/* モーダル 位置
	----------------------------------- */
	function modalPosition() {
		
		$('#hrefSearch').on('click', function(e){
			//ステップ１：駅検索
			var eki = $('#txteki').val();
			if($.trim(eki) == '') return;
			
			$('#lblEki').html(eki);
			
			$.ajax({
				beforeSend: function(xhr){
			    	 xhr.overrideMimeType("text/html;charset=UTF-8");
				},
				type: 'POST',
				url: '/areaajax/geteki/',
				dataType: 'text',
				data:{eki:eki,likeop:"1"},
				success: function(data) {
					console.log(data);
					if(data != undefined && $.trim(data) != ''){
						$('.error_message').hide();
						$('.list_expand').empty();
						
						//データフォーマット駅（都道府県）|都道府県CDー駅CD;...							
						  var vals = data.split(';');								  								  
						  for(var i = 0; i < vals.length; i++){
							  var splitVals = vals[i].split('|');
							  
							  var li = '<li><label class="list_wrap"><span class="box_radio"><input name="radio_dummy" type="radio" value="' + splitVals[1] + '" class="input_check" /></span><span class="box_txt">' + splitVals[0] + '</span></label></li>';
							  $('.list_expand').append(li);							  
						  }		
						  $('.modal_link').attr('href', '#stations')
						  $('.modal_link').trigger('click');
					}
					else{ //ヒットされてない、駅存在しない
						$('.error_message').show();
					}
				},
				error:function() {
					$('.list_expand').empty();
				}
			});
		})
		
		$('.modal_link').on('click', function(e){						
			  var _id = $(this).attr('href'),
			  _st = $(window).scrollTop(),
			  _wh = $(window).height(),
			  _ch = $(_id).height();
			  if (_wh > _ch) {
				$(_id).css({ 'top': _st + (_wh-_ch)*0.5 });
			  } else {
				$(_id).css({ 'top': _st + 20 });
			  };					
		});
		
		//駅選択してから→希望条件モーダル表示
		$('#btnNext').on('click', function(){
			if($('input[type=radio]:checked').length <= 0) return;
			$('#stations').hide();		
			$('.modal_link').attr('href', '#conditions_select')
			$('.modal_link').trigger('click');			
		});
		//駅選択してから→希望条件モーダル表示
		
		//検索
		$('.mod_btn_append_search').on('click', function(){
			var items=[];
			items.push({name:'search_type',value:'line'});

			var rad = $('input[type=radio]:checked').first();
			var prefs = rad.val().split('-');
			var pref = prefs[0];
			var cds = prefs[1].split('.');
			
			//駅
			for(var i = 0 ; i < cds.length ; i++){
				items.push({name:'target_'+i, value:pref + '-' + cds[i]});
			}
			
			//クッキー保存
			var eki = rad.parent().parent().find('.box_txt').html().split('(')[0];
			//alert(eki);
			CONS.saveSimpleEki(eki + '|' + rad.val());
			
			//賃料
			var tinryo = $('#sltinryo').val();
			if(tinryo != ''){
				var tinryos = tinryo.split('-');
				items.push({name:'tinryo1', value:tinryos[0]});
				items.push({name:'tinryo2', value:tinryos[1]});			
			}
			//間取り
			var madoriArray = ['10', '11', '12', '14', '21', '22', '24', '31', '32', '34', '41', '42', '44', '51'];
			var madori1 = $('#madori1').val();						
			var madori2 = $('#madori2').val();
			
			var start = '- 1';
			if(madori1 != '') start = madori1.replace('madori', '');			
			var end = '- 1';
			if(madori2 != '') end = madori2.replace('madori', '');
			
			if(start != '- 1' && end != '- 1' && parseInt(start) <= parseInt(end)){
				var startIndex = madoriArray.indexOf(start);
				var endIndex = madoriArray.indexOf(end);
				for(var index = startIndex; index <= endIndex; index++){					
					items.push({name:'madori' + madoriArray[index], value:'on'});
				}
			}
			else if(start != '- 1' && end == '- 1'){
				var startIndex = madoriArray.indexOf(start);
				for(var index = startIndex; index < madoriArray.length; index++){
					items.push({name:'madori' + madoriArray[index], value:'on'});
				}
			}
			else if(start == '- 1' && end != '- 1'){
				var endIndex = madoriArray.indexOf(end);
				for(var index = 0; index <= endIndex; index++){
					items.push({name:'madori' + madoriArray[index], value:'on'});
				}
			}

			items.push({name:'page',value:1});
			submit('/sp/rstobi/rstobi','POST',items);
		});
		
	};

	function submit(action, method, values) {
 	   var form = $('<form/>', {
	        action: action,
	        method: method
	    });
	    $.each(values, function() {
	        form.append($('<input/>', {
	            type: 'hidden',
	            name: this.name,
	            value: this.value
	        }));    
	    });
	    form.appendTo('body').submit();
	}

	/* モーダル 希望条件選択
	----------------------------------- */
	function modalConditionsSelect(){
		var $target = $('#conditions_select'),
			$type = $target.find('.list_btn_type li'),
			$down = $target.find('.box_list_content select[name=madori1]'),
			$up   = $target.find('.box_list_content select[name=madori2]'),
			data = {
				single: ['ワンルーム','1K','1DK','1LDK','2K','2DK'],
				double: ['1LDK','2K','2DK','2LDK','3K','3DK','3LDK'],
				family: ['2LDK','3K','3DK','3LDK','4K','4DK','4LDK','5K以上']
			},
			dataEn = {
					single: ['madori10','madori11','madori12','madori14','madori21','madori22'],
					double: ['madori14','madori21','madori22','madori24','madori31','madori32','madori34'],
					family: ['madori24','madori31','madori32','madori34','madori41','madori42','madori44','madori51']
			},
			id = null;

		$type.each(function(i){
			var _id = $(this).attr('class');
			$(this).on('click', function(e){
				id = _id;
				changeType();
			});
		});
		$down.on('change', function(e){
			changeRoom();
		});
		$up.on('change', function(e){
			changeRoom();
		});
		function changeType(){
			$type.each(function(i){
				if ($(this).attr('class') == id) {
					$(this).find('a').addClass('active');
				} else {
					$(this).find('a').removeClass('active');
				};
			});
			$down.val(dataEn[id][0]);
			$up.val(dataEn[id][dataEn[id].length-1]);
		};
		function changeRoom(){
			setTimeout(function(e){
				var _val1 = $down.val(),
					_val2 = $up.val(),
					_chk1 = 0,
					_chk2 = 0;
				$down.find('option').each(function(i){
					if ($(this).val() == _val1) {
						_chk1 = i;
						return false;
					};
				});
				$up.find('option').each(function(i){
					if ($(this).val() == _val2) {
						_chk2 = i;
						return false;
					};
				});
				if (_chk1 > _chk2) {
					$down.val(_val2);
					$up.val(_val1);
				};
			}, 1);
		};
	};


	/* 実行
	----------------------------------- */
	$(function() {
		inputFocus();
		areaChange();
		tabChange();
		modalPosition();
		modalConditionsSelect();
	});
})(this, document);